package edu.ccut.saturn.basecomponent.database.impl.sqlserver.handler.unused;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import edu.ccut.saturn.basecomponent.database.ISaturnSQL;
import edu.ccut.saturn.basecomponent.database.impl.AbstractSQLHandler;
import edu.ccut.saturn.basecomponent.database.impl.db2.DB2Attribute;
import edu.ccut.saturn.basecomponent.databasecomponent.Messages;
import edu.ccut.saturn.component.IDataInfo;
import edu.ccut.saturn.component.IDataItem;
import edu.ccut.saturn.component.SaturnComponentException;
import edu.ccut.saturn.component.SaturnData;
import edu.ccut.saturn.component.SaturnDataManager;

public class DB2SelectSQLHandler extends AbstractSQLHandler {

	public List<SaturnData> executeQuery(ISaturnSQL saturnSQL,
			Connection conn) throws SaturnComponentException {
		Statement stat = null;
		ResultSet rs = null;
		String sql = saturnSQL.getSql();
		List<SaturnData> list = new ArrayList<SaturnData>();
		if (conn != null) {
			try {
				stat = conn.createStatement();
				debug("QUERY_SQL=" + sql);
				rs = stat.executeQuery(sql);
				list = setListValueFromRs(SaturnDataManager.getInstance()
						.getSaturnDataInfo(saturnSQL.getSaturnDataFullKey()), rs);
			} catch (Exception e) {
				e.printStackTrace();
				throw new SaturnComponentException("query Exception");
			} finally {
				if (rs != null) {
					try {
						rs.close();
					} catch (SQLException e) {
						e.printStackTrace();
						throw new SaturnComponentException(
								"ResultSet close exception");
					}
				}
				if (stat != null) {
					try {
						stat.close();
					} catch (SQLException e) {
						e.printStackTrace();
						throw new SaturnComponentException(
								"Statment close exception");
					}
				}
			}
		} else {
			throw new SaturnComponentException(
					"Can not get Connection in database component"); //$NON-NLS-1$
		}
		return list;
	}

	/**
	 * 将ResultSet中的查询结果封装到list
	 * 
	 * @param data
	 * @param rs
	 * @return
	 * @throws Exception
	 */
	private List<SaturnData> setListValueFromRs(IDataInfo dataInfo, ResultSet rs)
			throws Exception {
		List<SaturnData> list = new ArrayList<SaturnData>();
		String packagename = dataInfo.getSpace();
		String getClassName = dataInfo.getType();
		// 得到查询结果的列数和列名称
		int columnCount = rs.getMetaData().getColumnCount();
		String[] columnNames = new String[columnCount];
		for (int i = 0; i < columnCount; i++) {
			columnNames[i] = rs.getMetaData().getColumnName(i + 1);
		}
		// 存放真正需要处理的key
		ArrayList<String> usedKeyArr = new ArrayList<String>();
		for (String key : dataInfo.keySet()) {
			for (String column : columnNames) {
				if (column.equalsIgnoreCase(key))
					usedKeyArr.add(key);
			}
		}
		SaturnData saturnData = null;
		while (rs.next()) {
			saturnData = SaturnDataManager.getInstance().createData(packagename,
					getClassName);
			for (int i = 0; i < usedKeyArr.size(); i++) {
				// 名称要变换为区分大小写的格式
				String usedKey = usedKeyArr.get(i);
				IDataItem dataItem = dataInfo.getDataItem(usedKey);
				if (dataItem != null) {
					String type = dataItem.getType();
					String javatype = dataItem.getJavaType();
					if (DB2Attribute.TIMESTAMP.equals(type)) {
						String date = null;
						if (rs.getDate(usedKey) != null) {
							date = rs.getString(usedKey);// 如果是时间，将时间戳的‘.0’去掉
							date = date.split("\\.")[0];
							// SimpleDateFormat format = new
							// SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							// date = format.format(rs.getDate(usedKey));
						}
						saturnData.set(usedKey, date);
					} else {
						setSaturnData(saturnData, usedKey, rs, javatype);
					}
				}
			}
			list.add(saturnData);
		}
		debug(Messages.getString("AbstractDatabaseCompononent.43")); //$NON-NLS-1$
		debug(Messages.getString("AbstractDatabaseCompononent.44")); //$NON-NLS-1$
		if (list.size() == 0) {
			return null;
		}
		return list;
	}

	/**
	 * 从rs中得到数据 并放到saturnData中，大数据处理除外
	 * 
	 * @param saturnData
	 *            容器
	 * @param key
	 *            键
	 * @param rs
	 *            值
	 * @param dataObjectType
	 *            判断条件
	 * @throws Exception
	 */
	private void setSaturnData(SaturnData saturnData, String key, ResultSet rs,
			String javaType) throws Exception {
		if (Integer.class.getName().equals(javaType)) {
			saturnData.set(key, rs.getInt(key));// TODO BigDecimal Integer 转换问题
		} else if (Double.class.getName().equals(javaType)) {
			saturnData.set(key, rs.getDouble(key));// TODO BigDecimal Double
			// 转换问题
		} else if (Float.class.getName().equals(javaType)) {
			saturnData.set(key, rs.getFloat(key));// TODO BigDecimal Float
			// 转换问题
		} else if (BigDecimal.class.getName().equals(javaType)) {
			saturnData.set(key, rs.getBigDecimal(key));
		} else if (Short.class.getName().equals(javaType)) {
			saturnData.set(key, rs.getShort(key));
		} else if (Long.class.getName().equals(javaType)) {
			saturnData.set(key, rs.getLong(key));
		} else if (java.sql.Date.class.getName().equals(javaType)) {
			saturnData.set(key, rs.getDate(key));
		} else if (String.class.getName().equals(javaType)) {
			saturnData.setString(key, rs.getString(key));
		} else if ("byte".equals(javaType)) {
			saturnData.set(key, rs.getByte(key));
		} else {
			saturnData.set(key, rs.getObject(key));
		}
	}

	public int executeUpdate(ISaturnSQL saturnSQL, Connection connection)
			throws SaturnComponentException {
		return 0;
	}

}
